# coding:utf-8
import os
import shutil


def find_all_files(folder):
    all_files = []
    for (dirpath, dirnames, filenames) in os.walk(folder):
        all_files.extend([os.path.join(dirpath, f) for f in filenames if f.endswith('.djvu')])
    all_files = [f for f in all_files]
    return all_files


# 随便找个含有竖线的文件，如果取消注释下面的第一行直接return fn，
# 仍然能得出正确页数，就表明重命名文件是多余的
def rename_special(fn):
    # return fn
    if '｜' in fn:
        renamed_fn = fn.replace('｜', '&')
        shutil.move(fn, renamed_fn)
        return renamed_fn
    return fn


def analyze_pages(exe, fn):
    cmd = rf' "{exe} " -e n "{fn}"'
    # print(cmd) #如果页数不正确，调试并复制出命令直接在cmd执行
    return os.popen(cmd, 'r').read().strip()


def append_line(line, file):
    with open(file, "a", encoding='utf-8') as fw:
        fw.write(line + os.linesep)


def count_folder_book_pages(exe, folder, statics_file):
    for fn in find_all_files(folder):
        renamed_fn = rename_special(fn)
        line = f'{renamed_fn.replace(folder, "")}\t{analyze_pages(exe, renamed_fn)}'
        append_line(line, statics_file)
        print(line)


if __name__ == "__main__":
    folder = os.path.abspath(os.getcwd())
    print(f'当前路径是{folder}')
    exe = r'D:\DjVuLibre\djvused.exe'
    statics_file = os.path.join(folder, "页数统计.txt")
    open(statics_file, 'w').close()
    count_folder_book_pages(exe, folder, statics_file)
    print('程序结束')
